package com.tongtong.middleware.util;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Pattern;

/**
 * @author wangqi
 */
public class URLDeal {

    private static final String URL_PATTERN = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]$";

    public static boolean isUrl(String str) {
        Pattern pattern = Pattern.compile(URL_PATTERN);
        return pattern.matcher(str).matches();
    }

    public static String getPath(String str) {
        try {
            URL url = new URL(str);
            return url.getPath();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getHost(String str) {
        try {
            URL url = new URL(str);
            return url.getHost();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getFileName(String str) {
        try {
            URL url = new URL(str);
            String path = url.getPath();
            return path.substring(path.lastIndexOf('/') + 1);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    public static boolean isInside(String str) {
        String prefix = str.substring(0, "cdn-nft".length());
        return "cdn-nft".equals(prefix);
    }
}
